<?php


class Test_mdl extends CI_Model
{
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function outputdata($data)
	{	

		$this->db->limit($data['QUESTNUM']); 
		
		if(!empty($data['TIMEID']) && isset($data['TIMEID']) && !empty($data['QBEFORE']) && isset($data['QBEFORE'])){
			if( $data['QBEFORE'] == 'N' ){
			
				$this->db->where('id >',$data['TIMEID']);
			
			}elseif( $data['QBEFORE'] == 'Y' ){
					
				$this->db->where('id <',$data['TIMEID']);
						
			}
			
		}
		$result = $this->db->where('enabled', 1)->order_by('id','desc')->get('cj_reward')->result_array();

		$res = array();
		foreach($result as $k=> $v){
			$tmp['drawNo'] = (int)$v['id'];
			$tmp['title'] = $v['infos'];
			$tmp['prices'] = (float)$v['singleprice'];
			$tmp['beginDate'] = date('Y-m-d',$v['beginDate']);
			$tmp['endDate'] = date('Y-m-d',$v['endDate']);
			$tmp['singleprice'] = $v['singleprice'];
			$tmp['imageUrl'] = site_url('/upload/reward/').'/'.$v['rewardpic'];
			$tmp['desc'] = $v['content'];
			$tmp['bHaveDrawed'] = $v['enabled'];
			$tmp['drawType'] = (int)$v['showtype'];
			$tmp['themename'] = '1';
			$tmp['minNumber'] = 1;
			$tmp['maxNumber'] = (int)$v['maxnumber'];
			$tmp['maxAllowSelectNumber'] = 3;
			$tmp['minAllowSelectNumber'] = 1;
			
			$tmp['attendCount'] = intval($this->_part($v['id']));
			$tmp['products'] = $this->getproducts($v['id']);
			$res[] = $tmp;
		}
		
		header( 'Content-Type:text/html; charset=utf-8', false );
		$outputdata['TAG'] = 'REWARD_LIST';
		$outputdata['DATA'] = $res;
		
		
		echo json_encode($outputdata);
		
	}
	
	/**
	 * 
	 * 活动奖品...
	 * @param int $id
	 */
	private function getproducts($id)
	{
		
		$flag = $this->db->select('product.productname,product.ptype,product.content,lottery.rnum,lottery.rewardid,stock.id')
				->where('lottery.rewardid',$id)
				->join('cj_products as product','lottery.productid = product.id')
				->join('cj_stock as stock','lottery.stockid = stock.id')
				->from('cj_lottery as lottery')
				->get()->result_array();
				
		$result = array();
		
		if(!empty($flag))
		{
			foreach($flag as $v)
			{
				$tmp['id'] = (int)$v['id'];
				$tmp['productName'] = $v['productname'];
				$tmp['ptype'] = (int)$v['ptype'];
				$tmp['content'] = $v['content'];
				$result[] = $tmp;
			}
		}
		return $result;
	}
	
	/**
	 * 
	 * 参与人数
	 * @param int $rewardid
	 */
	private function _part($rewardid)
	{

		$result = $this->db->select( 'count(distinct uid) as num' )
			->from( 'cj_lottery as lottery' )
			->where( 'lottery.uid !=','' )
			->where( 'lottery.rewardid',$rewardid )
			->get()
			->row_array();
			
		return $result['num'];
	}
	
}